/**
 * MIT License
 *
 * Copyright (c) 2024 小村程序员
 * Email: 397237738@qq.com
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.open.cobertura.agent;
 
import org.open.cobertura.core.instrument.CoberturaInstrument;
import org.open.cobertura.core.output.IOutputRuntimeData;
import org.open.cobertura.core.output.tcp.TCPOutputServer;
import org.open.cobertura.model.AgentOption;
import org.open.cobertura.model.OptionEnum;
import org.open.cobertura.params.AgentBuilder;
import org.open.cobertura.util.LoggingUtil;

import java.lang.instrument.Instrumentation;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.*;

/**
 * Cobertura Agent
 */
public class CoberturaAgent {
    private final static Logger logger = Logger.getLogger(CoberturaInstrument.class.getName());
    private final static ExecutorService executorService = Executors.newFixedThreadPool(1);
    public static void premain(String agentArgs, Instrumentation inst) {
        try {
            LoggingUtil.printBanner();
            LoggingUtil.setLogging();
            inst.addTransformer(new CoberturaTransformer(agentArgs));
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    IOutputRuntimeData outputRuntimeData=new TCPOutputServer();
                    ServerSocket serverSocket=outputRuntimeData.createOutputServer(AgentBuilder.getPortOption());
                    registerShutdownHook(inst,serverSocket);
                }
            });

            logger.info("OpenCobertura Attach Started");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    public static void agentmain(String agentArgs, Instrumentation inst) {
        registerShutdownHook(inst,null);
    }

    private static void registerShutdownHook(Instrumentation inst,ServerSocket serverSocket) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                serverSocket.close();
                executorService.shutdown();
                logger.info("Shutdown OpenCobertura Attach Service.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }));
    }
}